axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const booksList = document.querySelector('#tb')
const btnsift = document.querySelector('#btnsift')
const form = document.querySelector('#bookForm')
const tb = document.querySelector('#tb')
//渲染
const rendering = async (params) => {
  const bookRendering = await axios({
    url: '/api/getbooks',
    method: 'GET',
    params,
  })
  const html = bookRendering.data.data
    .map((item) => {
      return `<tr>
    <td>${item.id}</td>
    <td>${item.bookname}</td>
    <td>${item.author}</td>
    <td>${item.publisher}</td>
    <td><a href="#" data-id="${item.id}">删除</a></td>
  </tr>`
    })
    .join('')
  booksList.innerHTML = html
}
rendering()
//添加
form.addEventListener('submit', async function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  const add = await axios.post('/api/addbook', data)
  console.log(add)
  const {
    data: { msg, status },
  } = add
  alert(msg)
  if (status !== 201) return
  rendering()
  form.reset()
})
//筛选
btnsift.addEventListener('click', function () {
  const data = serialize(form, { hash: true })
  rendering(data)
})
//删除
tb.addEventListener('click', function (e) {
  if ((e.target.tagName = 'A')) {
    const id = e.target.dataset.id
    axios.get('/api/delbook?id=' + id)
    rendering()
  }
})
